import { Component, OnDestroy, OnInit, AfterViewInit, EventEmitter, HostListener } from '@angular/core';
import { merge, of as observableOf } from 'rxjs';
import { catchError, map, startWith, switchMap } from 'rxjs/operators';
import { Router } from '@angular/router';
import { MatDialog } from '@angular/material';
import { RestService } from '../services/rest.service';
import { environment } from 'environments/environment';
import { DataService } from 'app/services/data.service';

import * as _ from 'lodash';

@Component({
  templateUrl: './monitor.component.html',
  styleUrls: ['./monitor.component.css'],
})
export class MonitorComponent implements OnInit, OnDestroy, AfterViewInit {
  refreshInterval = environment.interval;
  refreshTask: any;
  selector = '.mat-drawer-content';

  pNumberPerPage = 50;
  position = 0;

  colNumber = 1;
  persons = [];
  allPersons = [];

  bedString = '';
  nurseId = -1;

  searchText = '';
  search: EventEmitter<any> = new EventEmitter();
  url = 'data/person';
  institution: any;

  @HostListener('window:resize', ['$event'])
  onResize(event) {
    this.calculateColNumber();
  }

  constructor(public dialog: MatDialog,
              private router: Router,
              private dataService: DataService,
              private rest: RestService) {
    this.institution = this.rest.getInstitution();
    this.calculateColNumber();
  }

  calculateColNumber() {
    const newNumber = (window.innerWidth - 200) / 250;
    this.colNumber = newNumber < 1 ? 1 : newNumber;
    this.pNumberPerPage = Math.ceil(window.innerHeight / 180) * this.colNumber;
  }

  navigateTo(item) {
    this.router.navigateByUrl('/monitor/' + item);
  }

  filterChanged(filter) {
    this.bedString = filter.bedString;
    this.nurseId = filter.nurse;
    this.search.emit(this.searchText);
  }

  initPersion() {
    merge(this.search)
    .pipe(
      startWith({}),
      switchMap(() => {
        const params = {
          institutionId: this.institution.id,
          checkoutTime: 1,
        };

        if (this.searchText) {
          params['name'] = this.searchText;
          return this.rest.getWithParams(this.url + '/search/monitorNamein', params);
        } else {
          if (this.bedString) {
            params['bedString'] = this.bedString;
            if (this.nurseId > 0) {
              params['nurseId'] = this.nurseId;
              return this.rest.getWithParams(this.url + '/search/monitorBedNurseIn', params);
            } else {
              return this.rest.getWithParams(this.url + '/search/monitorBedIn', params);
            }
          } else {
            if (this.nurseId > 0) {
              params['nurseId'] = this.nurseId;
              return this.rest.getWithParams(this.url + '/search/monitorNurseIn', params);
            } else {
              return this.rest.getWithParams(this.url + '/search/monitorAllIn', params);
            }
          }
        }
      }),
      map(data => {
        // check if this is still monitor
        this.allPersons = data['_embedded']['persons'];
        this.playAudio(this.allPersons);
        this.scheduleNext();

        const showPersons = [];
        const pLength = Math.max(this.position, this.pNumberPerPage);

        this.position = 0;
        for (let i = 0; i < pLength && i < this.allPersons.length; i++) {
          showPersons.push(this.allPersons[i]);
          this.position = i + 1;
        }

        return showPersons;
      }),
      catchError(() => {
        this.scheduleNext();
        return observableOf([]);
      })
    ).subscribe(data => {
      this.rest.updateArray(this.persons, data);
      this.dataService.updateGenEventData('Person');
    });
  }

  scheduleNext() {
    if (this.rest.getCurrentApp() !== 'monitor') {
      return;
    }

    if (this.refreshTask) {
      clearTimeout(this.refreshTask);
    }

    this.refreshTask = setTimeout(() => {
      if (this.rest.getCurrentApp() !== 'monitor') {
        return;
      }

      this.search.emit(this.searchText);
    }, this.refreshInterval);
  }

  doPlay(name) {
    /*
     01  设备离线
     02  体动报警
     03  呼吸报警
     04  做床边
     05  坐起
     06  尿湿报警
     07  心率报警
     08  用药提醒
     09  离床
     10  翻身提醒
     */
    const audio = new Audio();
    audio.src = '../../assets/audio/alarm'+name+'.wav';
    audio.load();
    audio.play();
  }

  playAudio(persons) {
    if (this.rest.getCurrentApp() !== 'monitor') {
      return;
    }

    for (let index = 0; index < persons.length; index++) {
      const person = persons[index];
      if (person.silent) {
        continue;
      }

      if (person.heartAlarmFlag && !person.hideHeartAlarm) {
        this.doPlay('07');
        return;
      }

      if (person.breatheAlarmFlag && !person.hideBreatheAlarm) {
        this.doPlay('03');
        return;
      }

      if (person.awayAlarmFlag && !person.hideAwayAlarm && person.awayAlarm) {
        this.doPlay('09');
        return;
      }

      if (person.sideAlarmFlag && !person.hideSideAlarm && person.sideAlarm) {
        this.doPlay('04');
        return;
      }

      if (person.upAlarmFlag && !person.hideUpAlarm && person.upAlarm) {
        this.doPlay('05');
        return;
      }

      if (person.wetAlarmFlag && !person.hideWetAlarm) {
        this.doPlay('06');
        return;
      }

      if (person.deviceAlarmFlag && !person.hideDeviceAlarm) {
        this.doPlay('01');
        return;
      }

      if (person.moveAlarmFlag && !person.hideMoveAlarm) {
        this.doPlay('02');
        return;
      }
      if (person.turnOverReminderAlarmFlag) { //yang 添加 翻身提醒报警 2019-06-13
        this.doPlay('11');
        return;
      }
    }
  }

  onScroll() {
    for (let i = this.position, j = 0; i < this.allPersons.length && j < this.pNumberPerPage; i++, j++) {
      this.persons.push(this.allPersons[i]);
      this.position = i + 1;
    }
  }

  ngAfterViewInit() {
    this.initPersion();
  }

  ngOnInit() {
  }

  ngOnDestroy() {
    if (this.refreshTask) {
      clearTimeout(this.refreshTask);
    }
  }
}
